import { useCrudForm } from "@/composables/useCrudForm";
import { onboardingFormConfig } from "../form-config";
import { formatDateTime } from "@/utils/xenUtils";
import SysHrOnboardingRequestBillApi from "../api/index";
import commonApi from "@/api/common";
import { reactive } from "vue";
import type {
  ISysHrOnboardingRequestBill,
  ISysHrOnboardingRequestBillVm,
} from "../api/interface";

/**
 * 入职申请单信息专用 Composable
 */
export function useOnboardingInfo() {
  // 创建API实例
  const api = SysHrOnboardingRequestBillApi();

  // API配置
  const apiConfig = {
    search: api.search,
    get: api.get,
    add: api.add,
    edit: api.edit,
    delete: api.delete,
    // 单据编号接口 - 适配器处理类型差异
    getBillCode: async () => {
      const result = await api.getBillCode();
      return { Data: result.Data || "" };
    },
  };

  // 选项数据加载器
  const optionLoaders = {
    groupId: async () => {
      const commonApiInstance = commonApi();
      const result = await commonApiInstance.GetParentsTree();
      // 转换为useCrudForm期望的格式
      return result.map((item: any) => ({
        Value: item.Value,
        Text: item.Text,
      }));
    },
    orgId: async () => {
      const result = await api.getOrganizations();
      // 转换为useCrudForm期望的格式
      return result.map((item: any) => ({
        Value: item.Value,
        Text: item.Text,
      }));
    },
    jobPositionId: async () => {
      // TODO: 实现工作岗位获取API
      // const commonApiInstance = commonApi();
      // const result = await commonApiInstance.GetJobPositions();
      // 暂时返回空数组，待API实现后修改
      return [];
    },
  };

  // 使用通用CRUD表单
  const crudForm = useCrudForm<ISysHrOnboardingRequestBill, ISysHrOnboardingRequestBillVm>(
    onboardingFormConfig,
    apiConfig,
    optionLoaders
  );

  // 岗位选项的局部状态管理（使用响应式对象）
  const positionOptions = reactive({
    job: [] as { value: string; text: string }[]
  });


  /**
   * 转换表单数据为API格式（新增）
   */
  const convertFormDataToApiFormatForCreate = (): ISysHrOnboardingRequestBillVm => {
    return {
      Entity: {
        // 工作信息
        OrgId: crudForm.pickerValues.orgId || crudForm.formData.orgId || null,
        GroupId: crudForm.pickerValues.groupId || crudForm.formData.groupId || null,
        JobPositionId: crudForm.pickerValues.jobPositionId || crudForm.formData.jobPositionId || null,
        ResumeId: (Array.isArray(crudForm.formData.resumeId) && crudForm.formData.resumeId.length > 0)
          ? crudForm.formData.resumeId[0]?.fileID
          : (Array.isArray(crudForm.formData.resumeId) ? null : (crudForm.formData.resumeId || null)),
        JoinWorkDate: null, // 新增时不设置参加工作日期
        HireDate: crudForm.formData.hireDate ? new Date(crudForm.formData.hireDate) : null,
        EmploymentType: crudForm.pickerValues.employmentType || null,
        ContractType: crudForm.pickerValues.contractType || null,
        ContractNo: crudForm.formData.contractNo || null,
        ContractStartDate: crudForm.formData.contractStartDate ? new Date(crudForm.formData.contractStartDate) : null,
        ContractEndDate: crudForm.formData.contractEndDate ? new Date(crudForm.formData.contractEndDate) : null,

        // 单据信息
        BillCode: crudForm.formData.billCode || null,
        BillStatus: null,
        WorkflowStatus: null,
        Remark: crudForm.formData.remark || null,
        Approver: null,
        ApprovalTime: null,

        // 员工基本信息字段设为null，由系统处理
        Name: null,
        StaffNo: null,
        BirthDate: null,
        Age: null,
        Gender: null,
        Ethnicity: null,
        HighestEducation: null,
        MaritalStatus: null,
        PhotoId: null,
        IdCardNo: null,
        IdCardFrontPhotoId: null,
        IdCardBackPhotoId: null,
        IdCardExpiryDate: null,
        HouseholdRegistration: null,
        NativePlace: null,
        PoliticalStatus: null,
        PartyJoinDate: null,
        PartyBranch: null,
        ArchiveLocation: null,
        ArchiveNo: null,
        ArchiveTransferOutDate: null,
        ArchiveTransferInDate: null,
        HomeAddress: null,
        Phone: null,
        Email: null,
        SalaryBank: null,
        SalaryAccount: null,
        BonusBank: null,
        BonusAccount: null,
        JoinWorkDate: null,
        WorkYears: null,
        ResignationDate: null,
        ResignationReason: null,
        ResignationType: null,
        BloodType: null,
        Hobbies: null,
        ExpectedStartDate: null,
        PersonMedicalId: null,
        SysPersonTrainExamId: null,
      },
      ActionName: null,
      IsMyApprove: null,
      Remark: null,
    };
  };

  /**
   * 转换表单数据为API格式（编辑）
   */
  const convertFormDataToApiFormatForEdit = (): ISysHrOnboardingRequestBillVm => {
    const originalData = crudForm.originalData.value;
    if (!originalData) {
      throw new Error("原始数据不存在");
    }

    return {
      Entity: {
        ID: originalData.ID || null,

        // 工作信息
        OrgId: crudForm.pickerValues.orgId || crudForm.formData.orgId || originalData.OrgId,
        GroupId: crudForm.pickerValues.groupId || crudForm.formData.groupId || originalData.GroupId,
        JobPositionId: crudForm.pickerValues.jobPositionId || crudForm.formData.jobPositionId || originalData.JobPositionId,
        ResumeId: (Array.isArray(crudForm.formData.resumeId) && crudForm.formData.resumeId.length > 0)
          ? crudForm.formData.resumeId[0]?.fileID
          : (Array.isArray(crudForm.formData.resumeId) ? null : (crudForm.formData.resumeId || originalData.ResumeId || null)),
        JoinWorkDate: crudForm.formData.joinWorkDate ? new Date(crudForm.formData.joinWorkDate) : originalData.JoinWorkDate,
        HireDate: crudForm.formData.hireDate ? new Date(crudForm.formData.hireDate) : originalData.HireDate,
        EmploymentType: crudForm.pickerValues.employmentType || originalData.EmploymentType,
        ContractType: crudForm.pickerValues.contractType || originalData.ContractType,
        ContractNo: crudForm.formData.contractNo || originalData.ContractNo,
        ContractStartDate: crudForm.formData.contractStartDate ? new Date(crudForm.formData.contractStartDate) : originalData.ContractStartDate,
        ContractEndDate: crudForm.formData.contractEndDate ? new Date(crudForm.formData.contractEndDate) : originalData.ContractEndDate,

        // 单据信息
        BillCode: crudForm.formData.billCode || originalData.BillCode,
        BillStatus: originalData.BillStatus,
        WorkflowStatus: originalData.WorkflowStatus,
        Remark: crudForm.formData.remark || originalData.Remark,
        Approver: originalData.Approver,
        ApprovalTime: originalData.ApprovalTime,

        // 继承原始数据中的其他字段
        Name: originalData.Name,
        StaffNo: originalData.StaffNo,
        BirthDate: originalData.BirthDate,
        Age: originalData.Age,
        Gender: originalData.Gender,
        Ethnicity: originalData.Ethnicity,
        HighestEducation: originalData.HighestEducation,
        MaritalStatus: originalData.MaritalStatus,
        PhotoId: originalData.PhotoId,
        IdCardNo: originalData.IdCardNo,
        IdCardFrontPhotoId: originalData.IdCardFrontPhotoId,
        IdCardBackPhotoId: originalData.IdCardBackPhotoId,
        IdCardExpiryDate: originalData.IdCardExpiryDate,
        HouseholdRegistration: originalData.HouseholdRegistration,
        NativePlace: originalData.NativePlace,
        PoliticalStatus: originalData.PoliticalStatus,
        PartyJoinDate: originalData.PartyJoinDate,
        PartyBranch: originalData.PartyBranch,
        ArchiveLocation: originalData.ArchiveLocation,
        ArchiveNo: originalData.ArchiveNo,
        ArchiveTransferOutDate: originalData.ArchiveTransferOutDate,
        ArchiveTransferInDate: originalData.ArchiveTransferInDate,
        HomeAddress: originalData.HomeAddress,
        Phone: originalData.Phone,
        Email: originalData.Email,
        SalaryBank: originalData.SalaryBank,
        SalaryAccount: originalData.SalaryAccount,
        BonusBank: originalData.BonusBank,
        BonusAccount: originalData.BonusAccount,
        // JoinWorkDate 已在上面根据表单数据处理，不需要重复赋值
        WorkYears: originalData.WorkYears,
        ResignationDate: originalData.ResignationDate,
        ResignationReason: originalData.ResignationReason,
        ResignationType: originalData.ResignationType,
        BloodType: originalData.BloodType,
        Hobbies: originalData.Hobbies,
        ExpectedStartDate: originalData.ExpectedStartDate,
        PersonMedicalId: originalData.PersonMedicalId,
        SysPersonTrainExamId: originalData.SysPersonTrainExamId,
      },
      ActionName: null,
      IsMyApprove: null,
      Remark: null,
    };
  };

  /**
   * 字段映射配置（API字段路径到表单字段的映射）
   */
  const fieldMapping = {
    // 单据信息
    billCode: "BillCode",
    billStatus: "BillStatus",
    workflowStatus: "WorkflowStatus",
    remark: "Remark",

    // 工作信息
    orgId: "OrgId",
    org: "Org.GroupName",
    groupId: "GroupId",
    group: "Group.GroupName",
    jobPositionId: "JobPositionId",
    jobPosition: "JobPosition.Name",
    resumeId: "ResumeId",
    joinWorkDate: "JoinWorkDate",
    hireDate: "HireDate",
    employmentType: "EmploymentType",
    contractType: "ContractType",
    contractNo: "ContractNo",
    contractStartDate: "ContractStartDate",
    contractEndDate: "ContractEndDate",

    // 员工基本信息
    name: "Name",
    staffNo: "StaffNo",
    phone: "Phone",
    gender: "Gender",
    idCardNo: "IdCardNo",

    // 流程信息
    approver: "Approver",
    approvalTime: "ApprovalTime",
  };

  /**
   * 加载入职申请单详情数据
   */
  const loadOnboardingDetail = async (id: string): Promise<{ success: boolean; isMyApprove?: boolean }> => {
    try {
      // 直接调用API获取完整响应
      const response = await api.get(id);

      if (response && response.Entity) {
        const detail = response.Entity;

        // 设置原始数据
        crudForm.originalData.value = detail;

        // 检查原始数据中的日期字段
        const dateFields = ["ApprovalTime", "HireDate", "ContractStartDate", "ContractEndDate", "JoinWorkDate"];
        dateFields.forEach(field => {
          if ((detail as any)[field]) {
            console.log(`原始数据中的日期字段 ${field}:`, (detail as any)[field]);
          }
        });

        // 先处理特殊字段，加载必要的选项数据
        await ensurePickerFieldsMapping(detail);

        // 然后使用通用转换，此时选项数据已经加载完成
        crudForm.convertApiDataToFormData(detail, fieldMapping);

        return {
          success: true,
          isMyApprove: response.IsMyApprove || false
        };
      }
      return { success: false };
    } catch (error) {
      console.error("获取入职申请单详情失败:", error);
      return { success: false };
    }
  };

  /**
   * 确保选择器字段正确映射
   */
  const ensurePickerFieldsMapping = async (apiData: any) => {
    // 处理单据编号
    if (apiData.BillCode) {
      crudForm.formData.billCode = apiData.BillCode;
    }

    // 处理单据状态
    if (apiData.BillStatus !== undefined) {
      const statusText = apiData.BillStatus === 0 || apiData.BillStatus === "草稿" ? "草稿" : "正文";
      crudForm.formData.billStatus = statusText;
      crudForm.pickerValues.billStatus = apiData.BillStatus.toString();
    }

    // 处理工作流状态显示
    if (apiData.WorkflowStatus !== undefined) {
      crudForm.formData.workflowStatus = apiData.WorkflowStatus || "";
    }

    // 处理用工形式（现在使用字符串）
    if (apiData.EmploymentType !== undefined) {
      crudForm.formData.employmentType = apiData.EmploymentType || "";
      crudForm.pickerValues.employmentType = apiData.EmploymentType || "";
    }

    // 处理劳动合同类型（现在使用字符串）
    if (apiData.ContractType !== undefined) {
      crudForm.formData.contractType = apiData.ContractType || "";
      crudForm.pickerValues.contractType = apiData.ContractType || "";
    }


    // 处理人事组织
    if (apiData.OrgId) {
      crudForm.formData.orgId = apiData.OrgId;
      crudForm.pickerValues.orgId = apiData.OrgId;
    }

    // 处理所属部门
    if (apiData.GroupId) {
      crudForm.formData.groupId = apiData.GroupId;
      crudForm.pickerValues.groupId = apiData.GroupId;
    }

    // 处理工作岗位 - 需要先加载部门的岗位选项
    if (apiData.JobPositionId && apiData.GroupId) {
      // 预加载部门的岗位选项，这样后续的通用转换就能正确处理
      await loadPositionsByDepartment(apiData.GroupId);
    }

    // 处理审批时间格式化
    if (apiData.ApprovalTime) {
      crudForm.formData.approvalTime = formatDateTime(apiData.ApprovalTime);
    }

    // 处理日期字段格式化
    const dateFields = ['hireDate', 'contractStartDate', 'contractEndDate', 'joinWorkDate'];
    dateFields.forEach(fieldKey => {
      const apiFieldKey = fieldKey.charAt(0).toUpperCase() + fieldKey.slice(1); // 首字母大写
      if (apiData[apiFieldKey]) {
        const formattedDateTime = formatDateTime(apiData[apiFieldKey]);
        crudForm.formData[fieldKey] = formattedDateTime ? formattedDateTime.split(' ')[0] : '';
      }
    });

    // 处理性别显示
    if (apiData.Gender !== undefined) {
      const genderText = apiData.Gender === 0 ? "女" : apiData.Gender === 1 ? "男" : "未知";
      crudForm.formData.gender = genderText;
    }

    // 处理简历文件回显
    if (apiData.ResumeId) {
      const getFileUrl = (fileId: string | null) => {
        if (!fileId) return "";
        return `${import.meta.env.VITE_BASE_URL}/api/_file/getfile/${fileId}`;
      };

      const resumeInfo = {
        name: "简历文件",
        url: getFileUrl(apiData.ResumeId),
        extname: "pdf",
        size: 0,
        fileID: apiData.ResumeId,
        id: apiData.ResumeId,
      };
      crudForm.formData.resumeId = [resumeInfo];
    } else {
      crudForm.formData.resumeId = [];
    }

  };

  /**
   * 创建入职申请单（两步提交流程）
   * 第一步：调用Add接口保存草稿
   * 第二步：调用Edit接口提交
   */
  const createOnboarding = async (): Promise<{
    success: boolean;
    data?: ISysHrOnboardingRequestBill;
    validation?: { valid: boolean; errors: Record<string, string>; firstErrorMessage?: string };
    error?: string;
  }> => {
    const validationResult = crudForm.validateAllFieldsWithDetails();

    if (!validationResult.valid) {
      return {
        success: false,
        validation: validationResult
      };
    }

    try {
      // 第一步：调用Add接口保存草稿
      const apiData = convertFormDataToApiFormatForCreate();
      const addResult = await crudForm.create(apiData);

      if (!addResult || !addResult.ID) {
        return {
          success: false,
          validation: validationResult,
          error: "保存草稿失败，请重试"
        };
      }

      // 第二步：调用Edit接口进行提交
      // 设置原始数据为第一步返回的结果，用于Edit接口
      crudForm.originalData.value = addResult;

      // 创建编辑数据格式进行提交
      const editApiData = convertFormDataToApiFormatForEdit();
      editApiData.Entity.WorkflowStatus = "提交中";

      const editResult = await crudForm.update(editApiData);

      if (!editResult) {
        return {
          success: false,
          validation: validationResult,
          error: "提交失败，数据已保存为草稿，请稍后重试"
        };
      }

      return {
        success: true,
        data: editResult,
        validation: validationResult
      };

    } catch (error) {
      console.error("创建入职申请单失败:", error);
      return {
        success: false,
        validation: validationResult,
        error: "提交过程中发生错误，请重试"
      };
    }
  };

  /**
   * 保存入职申请单（编辑）
   */
  const saveOnboarding = async (): Promise<{
    success: boolean;
    data?: ISysHrOnboardingRequestBill;
    validation?: { valid: boolean; errors: Record<string, string>; firstErrorMessage?: string };
    error?: string;
  }> => {
    const validationResult = crudForm.validateAllFieldsWithDetails();

    if (!validationResult.valid) {
      return {
        success: false,
        validation: validationResult
      };
    }

    // 验证关键数据
    if (!crudForm.originalData.value) {
      return {
        success: false,
        error: "原始数据丢失，请重新加载页面",
        validation: validationResult
      };
    }

    const apiData = convertFormDataToApiFormatForEdit();
    const result = await crudForm.update(apiData);

    return {
      success: result !== null,
      data: result || undefined,
      validation: validationResult
    };
  };

  /**
   * 更新表单配置中的部门数据和组织数据
   */
  const updateDepartmentData = async () => {
    try {
      const commonApiInstance = commonApi();
      const departmentData = await commonApiInstance.GetParentsTree();

      // 更新部门字段的数据
      if (onboardingFormConfig.groupId && departmentData) {
        onboardingFormConfig.groupId.departmentData = departmentData;
        onboardingFormConfig.groupId.optionsData = departmentData.map((item: any) => ({
          value: item.Value,
          text: item.Text,
        }));
      }

      // 获取并更新组织字段的数据
      const organizationData = await api.getOrganizations();
      if (onboardingFormConfig.orgId && organizationData) {
        onboardingFormConfig.orgId.departmentData = organizationData;
        onboardingFormConfig.orgId.optionsData = organizationData.map((item: any) => ({
          value: item.Value,
          text: item.Text,
        }));
      }

      return { departmentData, organizationData };
    } catch (error) {
      console.error("加载部门/组织数据失败:", error);
      return { departmentData: [], organizationData: [] };
    }
  };

  /**
   * 重写 initializeOptions 方法，同时更新部门数据
   */
  const initializeOptions = async (): Promise<boolean> => {
    // 先调用原始的 initializeOptions
    const result = await crudForm.initializeOptions();

    // 然后更新部门数据
    await updateDepartmentData();

    return result;
  };

  /**
   * 根据部门ID加载岗位列表
   */
  const loadPositionsByDepartment = async (departmentId: string): Promise<void> => {
    if (!departmentId) {
      // 如果没有部门ID，清空岗位选项
      positionOptions.job = [];
      return;
    }

    try {
      console.log("加载工作岗位列表，部门ID:", departmentId);
      const positions = await api.getSysJobPositions(departmentId);
      console.log("工作岗位列表:", positions);

      const positionOptionsList = positions.map((position: any) => ({
        value: position.Value || position.Id,
        text: position.Text || position.Name,
      }));

      // 更新局部状态
      positionOptions.job = positionOptionsList;

      // 同时更新表单配置中的选项数据，这样convertApiDataToFormData才能正确处理
      if (onboardingFormConfig.jobPositionId) {
        onboardingFormConfig.jobPositionId.options = positionOptionsList.map(option => option.text);
        onboardingFormConfig.jobPositionId.optionsData = positionOptionsList;
      }

      console.log("工作岗位选项更新完成:", positionOptionsList);
    } catch (error) {
      console.error("加载工作岗位列表失败:", error);
      // 加载失败时清空选项
      positionOptions.job = [];
      uni.showToast({
        title: "加载岗位列表失败",
        icon: "none",
      });
    }
  };

  /**
   * 处理部门选择变化，自动加载对应岗位
   */
  const handleDepartmentChange = async (fieldKey: string, departmentId: string): Promise<void> => {
    console.log('部门选择变化:', fieldKey, departmentId);

    // 如果是所属部门变化，清空工作岗位选择并重新加载
    if (fieldKey === "groupId") {
      // 清空岗位选择
      crudForm.formData.jobPositionId = "";
      crudForm.pickerValues.jobPositionId = "";

      // 加载对应岗位（包括清空的情况）
      await loadPositionsByDepartment(departmentId);
    }
  };

  /**
   * 检查岗位字段是否应该被禁用
   */
  const isPositionFieldDisabled = (fieldKey: string): boolean => {
    if (fieldKey === "jobPositionId") {
      return !crudForm.formData.groupId && !crudForm.pickerValues.groupId;
    }
    return false;
  };

  /**
   * 获取岗位选项（用于表单渲染）
   */
  const getPositionOptions = (fieldKey: string): { value: string; text: string }[] => {
    if (fieldKey === "jobPositionId") {
      console.log(`获取工作岗位选项，当前选项数量:`, positionOptions.job.length);
      return positionOptions.job || [];
    }
    return [];
  };

  /**
   * 获取岗位选项的显示文本数组（用于picker组件）
   */
  const getPositionOptionsText = (fieldKey: string): string[] => {
    const options = getPositionOptions(fieldKey);
    console.log(`获取${fieldKey}文本选项:`, options.map(option => option.text));
    return options.map(option => option.text);
  };

  return {
    // 继承通用CRUD表单的所有功能
    ...crudForm,

    // 重写 initializeOptions 方法
    initializeOptions,

    // 入职申请单信息专用方法
    loadOnboardingDetail,
    createOnboarding,
    saveOnboarding,
    updateDepartmentData,

    // API数据转换方法
    convertFormDataToApiFormatForCreate,
    convertFormDataToApiFormatForEdit,


    // 部门和岗位联动相关方法
    loadPositionsByDepartment,
    handleDepartmentChange,
    isPositionFieldDisabled,
    getPositionOptions,
    getPositionOptionsText,

    // 字段映射
    fieldMapping,
  };
}
